package server

import (
	"fmt"
	"sieve_admin_server_userpass/pkg/app"
	"sieve_admin_server_userpass/pkg/config"
	"sieve_admin_server_userpass/pkg/im3/app/api"
	"sieve_admin_server_userpass/pkg/log"
	"sieve_admin_server_userpass/pkg/rand"
	"sieve_admin_server_userpass/pkg/timesched"
	"time"
)

var (
	fReportAt = config.String("im.reportops.sched", fmt.Sprintf("m%ds%d", rand.In(1, 5), rand.In(0, 59)), "")
)

func init() {
	app.OnStart(func() {
		app.Async(func() {
			sch, err := timesched.Parse(*fReportAt)
			if err != nil {
				log.Fatal(err)
			}
			sch.Start(reportUserOps)
		})
		reportUserOps(time.Now())
	})
}

func reportUserOps(t time.Time) {
	tt := t.Add(-time.Hour)
	from := time.Date(tt.Year(), tt.Month(), tt.Day(), tt.Hour(), 0, 0, 0, tt.Location()).Unix()
	to := from + 60*60
	rows, err := db.Query("SELECT `Uid`,Count(*) FROM `app_op_log` WHERE `CreateTime`>=? AND `CreateTime`<? GROUP BY `Uid`", from, to)
	if err != nil {
		log.Err(err)
		return
	}
	defer rows.Close()
	list := []*api.OpsData{}
	for rows.Next() {
		d := &api.OpsData{}
		if err := rows.Scan(&d.Uid, &d.Cnt); err != nil {
			log.Err(err)
			return
		}
		list = append(list, d)
	}
	if len(list) == 0 {
		return
	}
	if err := api.ReportUserOps(tt, list); err != nil {
		log.Err(err)
	}
}
